package demo0506;

import javax.imageio.IIOException;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class Test1 {
        public static void main(String[] args) {

            String fileName = "name1.txt";
            String data = "123456";

            writeToFile(fileName, data);

            String content = readFromFile(fileName);
            System.out.println("从文件读取的内容: " + content);
        }

        private static void writeToFile(String fileName, String data) {
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
                writer.write(data);
                System.out.println("数据已成功写入文件！");
            } catch (IOException e) {
                System.err.println("写入文件时出错: " + e.getMessage());
            }
        }

        private static String readFromFile(String fileName) {
            StringBuilder content = new StringBuilder();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(fileName), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            } catch (IOException e) {
                System.err.println("读取文件时出错: " + e.getMessage());
            }

            return content.toString();
        }
    }

